import XLSX, { ColInfo } from 'xlsx'
import FileSaver from 'file-saver'

export const exportData = (xlsxDatas: any[][]) => {
  const userWorkSheet = XLSX.utils.aoa_to_sheet(xlsxDatas)
  return {
    xslx: (cols?: ColInfo[]) => {
      // 格式化表格数据
      const s2ab = (s: any) => {
        const buf = new ArrayBuffer(s.length)
        const view = new Uint8Array(buf)
        for (let i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xff
        return buf
      }
      const workbook = XLSX.utils.book_new()
      workbook.SheetNames = ['shee1']
      workbook.Sheets['shee1'] = userWorkSheet
      workbook.Sheets['shee1']['!cols'] = cols
      /* bookType can be 'xlsx' or 'xlsm' or 'xlsb' */
      const wbout = XLSX.write(workbook, { bookType: 'xlsx', bookSST: false, type: 'binary' })
      /* the saveAs call downloads a file on the local machine */
      // console.log(new Blob([s2ab(wbout)], { type: '' }))
      return {
        save: (filename: string) => {
          FileSaver.saveAs(new Blob([s2ab(wbout)], { type: '' }), `${filename}.xlsx`)
        }
      }
    },
    csv: () => {
      return {
        save: (filename: string) => {
          FileSaver.saveAs(
            new Blob(['\uFEFF' + XLSX.utils.sheet_to_csv(userWorkSheet)], {
              type: 'text/plaincharset=utf-8'
            }),
            `${filename}.csv`
          )
        }
      }
    }
  }
}
